package com.my.mygaode

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager

/**
 * @ClassName ViewPageExt
 * @Description TODO
 * @Author mwj
 * @Date 2023/7/18 15:36
 * @Version 1.0
 **/


/**
 * Fragment形式的ViewPager
 * @receiver ViewPager
 * @param fm FragmentManager
 * @param mTitles ArrayList<String>?
 * @param mFragment [@kotlin.ExtensionFunctionType] Function1<ArrayList<Fragment>, Unit>
 * @return ViewPager
 */
fun ViewPager.fragmentViewPagerAdapter(
    fm: FragmentManager,
    mTitles: ArrayList<String>?=null,
    mFragment: ArrayList<Fragment>.() -> Unit,

    ): ViewPager {
    val mFragments = ArrayList<Fragment>().apply(mFragment)
    offscreenPageLimit = if (mFragments.size >= 2) mFragments.size - 1 else mFragments.size
    adapter = object : FragmentPagerAdapter(fm) {
        override fun getCount(): Int {
            return mFragments.size
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return if (mTitles.isNullOrEmpty()) "" else mTitles[position]
        }

        override fun getItem(position: Int): Fragment {
            return mFragments[position]
        }
    }
    return this
}


/**
 * ViewPager的监听事件
 * @receiver ViewPager
 * @param onPageScrolled Function3<[@kotlin.ParameterName] Int, [@kotlin.ParameterName] Float, [@kotlin.ParameterName] Int, Unit>
 * @param onPageScrollStateChanged Function1<[@kotlin.ParameterName] Int, Unit>
 * @param onPageSelected Function1<[@kotlin.ParameterName] Int, Unit>
 */
fun ViewPager.pageChangedListener(
    onPageScrolled: (
        position: Int,
        positionOffset: Float,
        positionOffsetPixels: Int
    ) -> Unit = { _, _, _ -> },
    onPageScrollStateChanged: (state: Int) -> Unit = { _ -> },
    onPageSelected: (position: Int) -> Unit = { _ -> },
) {
    addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
        override fun onPageScrolled(
            position: Int,
            positionOffset: Float,
            positionOffsetPixels: Int
        ) {
            onPageScrolled.invoke(position, positionOffset, positionOffsetPixels)
        }

        override fun onPageSelected(position: Int) {
            onPageSelected.invoke(position)
        }

        override fun onPageScrollStateChanged(state: Int) {
            onPageScrollStateChanged.invoke(state)
        }

    })
}
